import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/api/http_server/file_collection.dart';
import 'package:loxen/api/http_server/like.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/format_time.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:provider/provider.dart';

class _ItemViewModel extends ChangeNotifier {
  InspirationInfo entity;

  _ItemViewModel();

  void notifier() {
    notifyListeners();
  }
}

//灵感Item
class ItemWidget extends StatelessWidget with LikeMixin, FileCollectionMixin {
  final InspirationInfo entity;
  static const Widget empty = const SizedBox.shrink();
  final _ItemViewModel _itemViewModel = _ItemViewModel();
  final bool isMy;

  ItemWidget({Key key, this.entity, this.isMy = false}) : super(key: key);

  Widget swipView() {
    CustomLayoutOption option = CustomLayoutOption(startIndex: 0, stateCount: 3).addTranslate([
      Offset(-657.w, 0),
      Offset(-65.w, 0),
      Offset(527.w, 0),
      Offset(1109.w, 0),
    ]).addScale([
      1,
      1,
      0.95,
    ], Alignment.center);
    return Swiper(
      layout: SwiperLayout.CUSTOM,
      customLayoutOption: option,
      loop: true,
      itemWidth: 582.w,
      itemHeight: 400.h,
      scale: 0.9,
      itemCount: entity.images.length,
      itemBuilder: (context, index) {
        return CachedNetworkImage(
          width: 582.w,
          height: 400.h,
          imageUrl: ImageUrlUtil.getClean(entity.images[index], w: 580),
          fit: BoxFit.cover,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    _itemViewModel.entity = entity;
    return ChangeNotifierProvider.value(
      value: _itemViewModel,
      child: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            height: 400.h,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context)
                    .pushNamed(Routes.inspiration_detail, arguments: entity)
                    .then((value) {
                  _itemViewModel.notifier();
                });
              },
              child: Stack(
                children: <Widget>[
                  Container(
                    child: entity.images != null
                        ? swipView()
                        : Image.network(
                            entity.cover,
                            width: 582.w,
                            fit: BoxFit.cover,
                            height: 400.h,
                          ),
                    height: double.infinity,
                  ),
                  entity.tag != null && entity.tag != ''
                      ? Positioned(
                          top: 28.h,
                          child: Stack(
                            children: <Widget>[
                              Image.asset(
                                'images/orangeBg.png',
                                width: 50,
                                height: 20,
                                fit: BoxFit.cover,
                              ),
                              Padding(
                                  padding: EdgeInsets.only(left: 23.w, top: 2.h),
                                  child: Text(
                                    entity.tag,
                                    style: TextStyle(
                                        fontSize: 20.sp,
                                        fontWeight: FontWeight.w500,
                                        color: Colors.white),
                                  ))
                            ],
                          ))
                      : empty,
                ],
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Expanded(
                  child: Text(
                    entity.title,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 27.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                Padding(
                    padding: EdgeInsets.only(right: 36.w),
                    child: Text(
                      FormatTime.readTimestamp(entity.add_time),
//                      FormatTime.readTimestamp(entity.add_time),
                      style: TextStyle(
                          color: Color(0xFF999999), fontSize: 20.sp, fontWeight: FontWeight.w500),
                    ))
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 30.h),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (!isMy) {
                        Navigator.of(context).pushNamed(Routes.mine_user_info,
                            arguments: entity.user.userId.toString());
                      }
                    },
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: 52.w,
                          height: 52.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: NetworkImage(
                                  entity.user.portrait,
                                ),
                                fit: BoxFit.cover),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 15.w),
                          child: Text(
                            entity.user.nickname,
                            style: TextStyle(color: Color(0xFF666666), fontSize: 21.sp),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                        } else {
                          if (entity.is_like == 0) {
                            like(ContentType.IDEA_ARTICLE, entity.id.toString()).listen((event) {
                              if (event != null) {
                                entity.is_like = 1;
                                entity.like_num = event.like_num;
                                _itemViewModel.notifier();
                              }
                            });
                          } else {
                            unLike(ContentType.IDEA_ARTICLE, entity.id.toString()).listen((event) {
                              if (event != null) {
                                entity.is_like = 0;
                                entity.like_num = event.like_num;
                                _itemViewModel.notifier();
                              }
                            });
                          }
                        }
                      },
                      child: Builder(builder: (context) {
                        int isLike =
                            context.select<_ItemViewModel, int>((value) => value.entity.is_like);
                        return Stack(
                          alignment: Alignment.centerLeft,
                          children: <Widget>[
                            Image.asset(
                              isLike == 0 ? "images/like.png" : "images/like_active.png",
                              width: 30.w,
                              height: 30.w,
                              fit: BoxFit.cover,
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                left: 37.w,
                                top: 4.h,
                              ),
                              child: Text(
                                '${entity.like_num}',
                                style: TextStyle(
                                    fontSize: 22.sp,
                                    color: entity.is_like == 0
                                        ? Color(0xFF999999)
                                        : Color(0xFF0CABCB)),
                              ),
                            )
                          ],
                        );
                      }),
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () {
                        Navigator.of(context)
                            .pushNamed(Routes.inspiration_detail, arguments: entity)
                            .then((value) {
                          _itemViewModel.notifier();
                        });
                      },
                      child: Builder(builder: (context) {
                        int comment = context
                            .select<_ItemViewModel, int>((value) => value.entity.comment_num);
                        return Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(top: 5.h),
                          child: Stack(
                            alignment: Alignment.centerLeft,
                            children: <Widget>[
                              Image.asset(
                                'images/comment.png',
                                width: 30.w,
                                height: 30.w,
                                fit: BoxFit.cover,
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 37.w),
                                child: Text(
                                  '$comment',
                                  style: TextStyle(fontSize: 22.sp, color: Color(0xFF999999)),
                                ),
                              )
                            ],
                          ),
                        );
                      }),
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(right: 30.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () async {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                          return;
                        }
                        if (entity.is_collect == 0) {
                          Navigator.of(context).pushNamed(Routes.master_file_add, arguments: {
                            'type': FileType.INSPIRATION,
                            'id': entity.id.toString()
                          }).then((value) {
                            if (value) {
                              entity.collect_num += 1;
                              entity.is_collect = 1;
                              _itemViewModel.notifier();
                            }
                          });
                        } else {
                          bool data = await showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                    title: Text('提示'),
                                    content: Text(
                                      '是否取消收藏？',
                                      style: TextStyle(color: Colors.black),
                                    ),
                                    actions: <Widget>[
                                      FlatButton(
                                        child: Text(StringResources.qu_xiao),
                                        onPressed: () => Navigator.of(context).pop(),
                                      ),
                                      FlatButton(
                                        child: Text(StringResources.que_ding),
                                        onPressed: () {
                                          Navigator.of(context).pop(true);
                                        },
                                      ),
                                    ],
                                  ));
                          if (data != null && data) {
                            unCollection(ContentType.IDEA_ARTICLE, entity.id.toString()).listen(
                                (event) {
                              if (event == 200) {
                                entity.is_collect = 0;
                                entity.collect_num -= 1;
                                Toast.show(StringResources.qu_xiao_shou_cang, context);
                                _itemViewModel.notifier();
                              } else {
                                Toast.show(StringResources.qu_xiao_shou_cang_shi_bai, context);
                              }
                            },
                                onError: (error) =>
                                    Toast.show(StringResources.wang_luo_yi_chang, context));
                          }
                        }
                      },
                      child: Builder(
                        builder: (BuildContext context) {
                          int collect = context
                              .select<_ItemViewModel, int>((value) => value.entity.is_collect);
                          return Stack(
                            alignment: Alignment.centerLeft,
                            children: <Widget>[
                              Image.asset(
                                collect == 0 ? "images/collect.png" : "images/collected.png",
                                width: 30.w,
                                height: 30.w,
                                fit: BoxFit.cover,
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                  left: 37.w,
                                  top: 4.h,
                                ),
                                child: Text(
                                  '${entity.collect_num}',
                                  style: TextStyle(
                                      fontSize: 22.sp,
                                      color: collect == 0 ? Color(0xFF999999) : Color(0xFF0CABCB)),
                                ),
                              )
                            ],
                          );
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
